﻿//-----------------------------------------------------------------------
// <copyright file="ObservableQueue.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>15/07/2012</date>
//-----------------------------------------------------------------------
using ConsoleHoster.Common.Utilities;
using System;
using System.Collections.ObjectModel;

namespace ConsoleHoster.Model
{
    public sealed class ObservableQueue<T> : ObservableCollection<T>
    {
        private int queueSize;
        private readonly Object syncRoot = new Object();

        public ObservableQueue(int size)
        {
            if (size < 0)
            {
                throw new ArgumentOutOfRangeException("size");
            }

            this.queueSize = size;
        }

        protected override void InsertItem(int index, T item)
        {
            new Action(() =>
                {
                    int tmpInsertionIndex = index;
                    if (this.queueSize != 0 && this.Count >= this.queueSize)
                    {
                        this.RemoveAt(0);
                        tmpInsertionIndex = index - 1;
                    }

                    base.InsertItem(tmpInsertionIndex, item);
                }).SyncronizeCallByLocking(this.syncRoot);
        }
    }
}